<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue';
import {
  showToast,
  navigateTo,
  showLoading,
  eventCenter,
  getCurrentInstance,
  showModal,
} from '@tarojs/taro';
import ItemTypeSelectDepartment from '../../item-receive/edit-single/components/item-type-select-department.vue';
import StoreRoomForm from './store-room-form.vue';
import { ADD_WAREHOUSE_APPLY } from '/@/api/modules/flow-path/flow-path-warehouse';
import { QUERY_FTD_FOR_ADD_FLOW } from '/@/api/modules/flow-path/flow-path-template';
import ApproveProcessList from '../../../approve/edit/components/approve-process-list/approve-process-list.vue';
import { ItemTypeDto } from '../index';
import { FIND_ONE, SAVE, DELETE } from '/@/api/modules/flow-path/flow-path-draft';
import { LOGIN_APP } from '/@/api/modules/base/app-sys-user';
import { STORE_ROOM_APPROVE_TEMPLATE_CODE } from '/@/common/constant';
import { QUERY_APP_FLOW_PATH_RECORD_DETAIL } from '/@/api/modules/flow-path/flow-path';
const params = getCurrentInstance().router?.params as {
  /**
   * 审批id
   */
  id?: string;
};
const formState: {
  deptName: string;
  desc: string;
  amount: string;
  list: FlowpathWarehouse.ApplyToolInfoDto[];
  templateCode: string;
  flowGraphAddFlow?: FlowPathTemplateApi.FlowGraph;
} = reactive({
  deptName: '',
  desc: '',
  amount: '',
  list: [],
  templateCode: '',
  flowGraphAddFlow: {},
});

const state = reactive<{
  /**
   * 审批流程配置图结构体
   */
  flowGraph?: FlowPathTemplateApi.FlowGraph;
  /**
   * 审批流程配置图结构体
   */
  flowGraphAddFlow?: FlowPathTemplateApi.FlowGraph;
  userId?: string;
  templateId?: string;
  productList?: FlowPathDraftApi.Product2[];
}>({
  flowGraph: {},
  flowGraphAddFlow: {},
  userId: '',
  templateId: '',
  productList: [],
});

const itemTypeFormRef = ref<InstanceType<typeof StoreRoomForm>>();

/**
 * 子组件的state.list赋值给formState
 */
function updateFormState() {
  formState.list = [];
  itemTypeFormRef.value?.dynamicFormRef.list.forEach((item: ItemTypeDto) => {
    formState.list.push({
      toolTypeName: item.toolTypeName,
      toolName: item.toolName,
      spec: item.spec,
      price: Number(item.price),
      amount: item.amount,
    });
  });
}

/**
 * true: 表格全部类容已经填写，false：还有表格字段没填写
 */
function checkForm() {
  /**
   * resultList: 填写类容为true，没填写为false
   */
  const resultList: boolean[] = [];
  formState.list.forEach((item) => {
    resultList.push(item.toolTypeName && item.toolTypeName?.length > 0 ? true : false);
    resultList.push(item.toolName && item.toolName?.length > 0 ? true : false);
    resultList.push(item.amount && item.amount > 0 ? true : false);
  });
  return resultList.every((item) => {
    return item;
  });
}

/**
 * 提交审批
 */
function submit() {
  updateFormState();
  if (!formState.deptName) {
    showToast({ title: '部门不能为空', icon: 'error' });
    return;
  }
  if (!formState.desc) {
    showToast({ title: '说明不能为空', icon: 'error' });
    return;
  }

  if (!checkForm()) {
    showToast({ title: '物资字段不能为空', icon: 'error' });
    return;
  }

  showLoading();
  let total = 0;
  formState.list.forEach((item) => {
    if (item.amount) {
      total += item.amount * Number(item.price);
    }
  });
  formState.amount = total.toFixed(2).toString();
  formState.flowGraphAddFlow = state.flowGraphAddFlow;
  formState.templateCode = STORE_ROOM_APPROVE_TEMPLATE_CODE;
  //物品领用
  ADD_WAREHOUSE_APPLY(formState)
    .then((res) => {
      if (res.comResp?.code === 100) {
        navigateTo({
          url: '/pages/police-security/submit-success/index',
        });
      }
    })
    .then(() => {
      deleteDraft(STORE_ROOM_APPROVE_TEMPLATE_CODE);
    });
}

function deptChange(_: string, deptName: string) {
  formState.deptName = deptName;
}

onMounted(() => {
  eventCenter.on(getCurrentInstance().router?.onShow as string, () => {
    //清理数据，当成功页面返回的时候，显示初始状态

    formState.deptName = '';
    formState.desc = '';
    formState.amount = '';
    formState.list = [];
  });
  //查询流程
  queryDetail();
});

function saveDraft() {
  if (state.userId) {
    saveDraftByRequest();
  } else {
    showLoading();
    LOGIN_APP().then((res) => {
      state.userId = res.sysUserDto.id;
      saveDraftByRequest();
    });
  }
}

/**
 * 查询审批模版详情
 * @param code 审批模版code
 */
function queryDetail() {
  showLoading();
  QUERY_FTD_FOR_ADD_FLOW({ code: STORE_ROOM_APPROVE_TEMPLATE_CODE }).then((res) => {
    state.flowGraph = res.flowpathTemplateDto?.flowGraph;
    state.flowGraphAddFlow = res.flowpathTemplateDto?.flowGraphAddFlow;
    if (params.id) {
      queryApprovedDetail(params.id);
    } else {
      queryDraft(STORE_ROOM_APPROVE_TEMPLATE_CODE);
    }
  });
}

function saveDraftByRequest() {
  showLoading();
  SAVE({
    userId: state.userId,
    flowpathRecordDto: {
      templateId: state.templateId,
      templateCode: STORE_ROOM_APPROVE_TEMPLATE_CODE,
    },
    flowGraph: state.flowGraph,
    flowGraphAddFlow: state.flowGraphAddFlow,
    deptName: formState.deptName,
    desc: formState.desc,
    productList: itemTypeFormRef.value?.dynamicFormRef.list.map((item: ItemTypeDto) => {
      return {
        toolTypeName: item.toolTypeName,
        toolName: item.toolName,
        spec: item.spec,
        price: Number(item.price),
        amount: item.amount,
      };
    }),
  }).then((res) => {
    if (res.comResp?.code === 100) {
      showModal({
        title: '保存草稿成功',
        showCancel: false,
        content: '下次进入申请页面可继续填写表单内容',
      });
    }
  });
}

function queryDraft(code: string) {
  showLoading();
  LOGIN_APP().then((res) => {
    state.userId = res.sysUserDto.id;

    FIND_ONE({ templateCode: code, userId: state.userId }).then((res) => {
      if (res.flowpathRecordDto) {
        showModal({
          title: '继续填写',
          content: '你有未提交的内容，是否载入草稿继续填写？',
          success: function (result) {
            if (result.confirm) {
              state.flowGraph = res.flowGraph;
              state.flowGraphAddFlow = res.flowGraphAddFlow;
              formState.deptName = res.deptName || '';
              formState.desc = res.desc || '';
              state.productList = res.productList as FlowPathDraftApi.Product2[];
            } else if (result.cancel) {
              deleteDraft(code);
            }
          },
        });
      }
    });
  });
}

function deleteDraft(code: string) {
  DELETE({ templateCode: code, userId: state.userId });
}

/**
 * @function 获取审批详情
 */
function queryApprovedDetail(id: string) {
  showLoading();
  QUERY_APP_FLOW_PATH_RECORD_DETAIL({ id }).then((res) => {
    console.log('store-room approve detail:' + res);
  });
}
</script>
<template>
  <scroll-view class="app-page__wrapper" :scroll-y="true" :lower-threshold="100">
    <view class="store-room-edit__wrapper">
      <!-- 选择部门 -->
      <nut-form>
        <nut-form-item label="申领部门" required>
          <item-type-select-department :dept-name="formState.deptName" @on-change="deptChange" />
        </nut-form-item>
        <nut-form-item label="申领说明" required>
          <nut-input
            placeholder="请填写"
            type="text"
            v-model="formState.desc"
            input-align="right"
            :border="false"
          />
        </nut-form-item>
      </nut-form>
      <!-- 选择领用物品 -->
      <store-room-form ref="itemTypeFormRef" :product-list="state.productList" />
      <!-- 流程图 -->
      <approve-process-list
        v-if="state.flowGraphAddFlow && Object.keys(state.flowGraphAddFlow).length > 0"
        :flow-graph-add-flow="state.flowGraphAddFlow"
      />
    </view>
  </scroll-view>
  <view class="store-room-edit__footer">
    <nut-button class="store-room-edit__footer-btn" block color="#bbb" @click="saveDraft()">
      存草稿
    </nut-button>
    <nut-button block type="info" @click="submit()"> 提交 </nut-button>
  </view>
</template>
<style lang="scss">
.store-room-edit {
  &__wrapper {
    padding: 20px 20px;
  }
  &__footer {
    padding: 20px 20px;
    background-color: #fff;
    display: flex;
  }
  &__footer-btn {
    flex: 1;
    margin: 0 10px !important;
  }
}
</style>
